from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from core.config import settings
from core.security import create_access_token, verify_password
from models.admin import Admin
from schemas.admin import TokenResp
from dependencies.auth import get_current_admin 

router = APIRouter(prefix="/admin", tags=["admin"])   # tags 方便 Swagger 分组

@router.post("/login", response_model=TokenResp, summary="管理员登录")
async def login(form: OAuth2PasswordRequestForm = Depends()):
    admin = await Admin.get_or_none(username=form.username)
    if not admin or not admin.verify_password(form.password):
        raise HTTPException(400, "Incorrect username or password")
    token = create_access_token(
        sub=admin.username,
        exp_delta=timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
    )
    return TokenResp(access_token=token)

# 示例受保护接口
@router.get("/me", summary="当前管理员信息")
async def read_me(admin: Admin = Depends(get_current_admin)):
    from models.admin import AdminPydantic
    return await AdminPydantic.from_tortoise_orm(admin)